package cz.proks.schoolpupilbook.gwt.core.handler;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;

import cz.proks.schoolpupilbook.gwt.core.ResultNotifiable;
import cz.proks.schoolpupilbook.gwt.service.ServiceFactory;
import cz.proks.schoolpupilbook.gwt.service.UserCourseRelationService;
import cz.proks.schoolpupilbook.gwt.widget.common.UserCourseRelationForm;
import cz.proks.schoolpupilbook.gwt.widget.common.UserCourseRelationForm.SubmitEvent;
import cz.proks.schoolpupilbook.shared.domain.Course;
import cz.proks.schoolpupilbook.shared.domain.User;
import cz.proks.schoolpupilbook.shared.domain.UserCourseRelation;

public class UserCourseRelationFormHandler implements UserCourseRelationForm.SubmitEvent.SubmitEventHandler{
	@Override
	public void onSubmit(SubmitEvent event) {
		UserCourseRelationService userCourseRelationService = ServiceFactory.getUserCourseRelationService();
		UserCourseRelation userCourseRelation = createUserCourseRelation(event);
		
		userCourseRelationService.save(userCourseRelation, new ResultNotifiable<Void>() {
			
			@Override
			public void onSucces(Void object) {
				History.back();				
			}
			
			@Override
			public void onError(Throwable t) {
				Window.alert("Failed to user-course: " + t.getLocalizedMessage());
			}
		});
	}
	
	private UserCourseRelation createUserCourseRelation(SubmitEvent event) {
		UserCourseRelation userCourseRelation = new UserCourseRelation();
		
		User user = new User();
		Course course = new Course();
		
		user.setId(event.getStudentId());
		course.setId(event.getCourseId());
		
		userCourseRelation.setId(event.getId());
		userCourseRelation.setUser(user);
		userCourseRelation.setCourse(course);
		
		return userCourseRelation;
	}
}
